import { VNodeChild } from 'vue'

import { DialogOptions } from 'naive-ui'

// 虽然naiveUI提供了脱离上下文的 API，但是在实际使用中，结合pinia的状态管理，可以更好的管理事件

interface loadingStoreState {
  loading?: boolean
  description?: string
}

export const useLoadingStore = defineStore('eventBus-pageLoading', {
  state: (): loadingStoreState => ({
    loading: false,
    description: '',
  }),
  actions: {
    useLoading(description?: string) {
      this.loading = true
      this.description = description
    },
    hideLoading() {
      this.loading = false
      this.description = ''
    },
  },
})

interface MessageRender {
  // 信息内容
  content?: string | number | (() => VNodeChild)
  // 信息图标
  icon?: () => VNodeChild
  // 是否可关闭,默认不可关闭
  closable?: boolean
  // 信息类型,默认为info
  type?: 'info' | 'success' | 'warning' | 'error' | 'loading'
  // 持续时间,默认为3000
  duration?: number
}
interface MesaageStoreState {
  message: MessageRender
  messageShow: number
}
export const useMessageStore = defineStore('eventBus-message', {
  state: (): MesaageStoreState => ({
    message: {},
    messageShow: 0,
  }),
  actions: {
    useMessage(message: MessageRender) {
      this.messageShow++
      this.message = message
    },
    hideMessage() {
      this.messageShow = 0
      this.message = {}
    },
  },
})

interface DialogStoreState {
  dialog: DialogOptions
  dialogShow: number
}
export const useDialogStore = defineStore('eventBus-dialog', {
  state: (): DialogStoreState => ({
    dialog: {},
    dialogShow: 0,
  }),
  actions: {
    useDialog(dialog: DialogOptions) {
      this.dialogShow++

      const that = this
      const defaultConfig = {
        title: '警告',
        content: '是否确定',
        positiveText: '确认',
        negativeText: '取消',
        // 自动聚焦会导致焦点聚集在 close 图标上
        autoFocus: false,
        // 动画结束后重置状态
        onAfterLeave() {
          that.hideDialog()
        },
      }
      this.dialog = Object.assign(defaultConfig, dialog)
    },
    hideDialog() {
      this.dialogShow = 0
      this.dialog = {}
    },
  },
})

interface LoadingBarStoreState {
  loadingBarShow: boolean
}
export const useLoadingBarStore = defineStore('eventBus-loadingBar', {
  state: (): LoadingBarStoreState => ({
    loadingBarShow: false,
  }),
})
